package com.hjm.mall.config.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 将json转为int[]
 */
public class JsonIntArrayTypeHandler extends BaseTypeHandler<int[]> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, int[] parameter, JdbcType jdbcType) throws SQLException {
        // 将int[]转换为JSON字符串并设置到PreparedStatement中（如果需要）
        // 注意：在实际场景中，直接设置int[]到PreparedStatement可能更有意义，但这里为了示例我们转换为JSON
        String json = objectMapper.writeValueAsString(parameter);
        ps.setString(i, json);
    }

    @Override
    public int[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        if (json == null) {
            return null;
        }
        try {
            // 从JSON字符串中解析int[]
            JsonNode rootNode = objectMapper.readTree(json);
            if (!rootNode.isArray()) {
                throw new SQLException("Expected an array in JSON");
            }
            int[] array = new int[rootNode.size()];
            for (int i = 0; i < rootNode.size(); i++) {
                array[i] = rootNode.get(i).asInt();
            }
            return array;
        } catch (Exception e) {
            throw new SQLException("Error parsing JSON to int array", e);
        }
    }

    @Override
    public int[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getNullableResult(rs, rs.getMetaData().getColumnName(columnIndex));
    }

    @Override
    public int[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getNullableResult(cs.getResultSet(), columnIndex);
    }
}
